# -- coding: utf-8 -- 
# Name: port_scan

import optparse
from socket import *
from threading import *
screenLock = Semaphore(value=1)
def connscan(host,port):
    try:
        conn = socket(AF_INET,SOCK_STREAM)
        conn.connect((host,port))
        conn.send('quite simple\r\n')
        results = conn.recv(100)
        print "%s tcp open" % port
        print str(results)
    except:
        screenLock.acquire()
        print "%s tcp closed" % port
    finally:
        screenLock.release()
        conn.close()

def portscan(host,ports):
    try:
        ip = gethostbyname(host)
    except:
        print "can`t resolve %s , unknow host" % host
        return
    try:
        name = gethostbyaddr(ip)
        print "scan result for: " + name[0]
    except:
        print "scan result for:   " + ip
    setdefaulttimeout(1)
    for p in ports:
        print "scanning port "+ p
        connscan(host,int(p))

def main():
    parser = optparse.OptionParser('usage %prog -h <target host> -p <target ports> ')
    parser.add_option('-h', dest="host", type='string', help='spcify target host')
    parser.add_option('-p', dest="port", type='string', help='spcify target ports')
    options,args = parser.parse_args()
    host = options.host
    ports = str((options.ports).split(","))
    if host == None or ports == None:
        print parser.usage
        exit(0)
    portscan(host,ports)

main()